import logging
import os
import sys

log = logging.getLogger('config')

class SyncConfig:
    def __init__(self):
        self.id_              = None
        self.tx_ap_           = None
        self.init_db_         = False
        self.db_type_         = None
        self.db_opts_         = {}
        self.debug_           = False
        self.type_file_       = None
        self.sched_module_    = None
        self.sync_interval_   = 1
        self.quit_after_init_ = False
        
    def parse_opts(self):
        if '--help' in sys.argv or '-h' in sys.argv:
            self.print_usage()
            sys.exit(0)

        format = '%(name)-8s %(levelname)-8s | %(message)s'
        if '--debug' in sys.argv:
            logging.basicConfig(level=logging.DEBUG, format=format)
            self.debug_ = True
        else:
            logging.basicConfig(level=logging.INFO, format=format)
            
        self.init_db_ = '--init-db' in sys.argv
        self.quit_after_init_ = '--quit-after-init' in sys.argv

        self.id_ = self.get_env_var('NEON_ID', 'unassigned_id')
        tx_addr_spec = self.get_env_var('NEON_TX_ADDR', 'localhost:7001')
        if ':' not in tx_addr_spec:
            tx_addr = tx_addr_spec
            tx_port = 0
        else:
            tx_addr, tx_port = tx_addr_spec.split(':')

        self.type_file_ = self.get_env_var('NEON_TYPE_FILE', None)
	if self.type_file_ == '':
	    self.type_file_ = None

        self.sched_module_ = self.get_env_var('NEON_SCHED_MODULE', None)
	if self.sched_module_ == '':
	    self.sched_module_ = None
        
        self.db_type_ = self.get_env_var('NEON_DB_TYPE')
        for k in os.environ.keys():
            if k[:8] == 'NEON_DB_':
                opt = k[8:]
                self.db_opts_[opt] = os.environ[k]

        for i in sys.argv:
            o = i.split('=')
            if o[0] == '--tx-addr':
                if o[1] == '/':
                    tx_addr = o[1]
                    tx_port = 0
                else:
                    tx_addr, tx_port = o[1].split(':')
            elif o[0] == '--id':
                self.id_ = o[1]
            elif o[0] == '--type-file':
                self.type_file_ = o[1]
                
        self.tx_ap_ = tx_addr, int(tx_port)

        self.sync_interval_ = float(self.get_env_var('NEON_SYNC_INTERVAL'))

        # Print out configuration
        cfg = ['    ' + e + ': ' + str(getattr(self, e)) for e in dir(self)
               if (e[:2] != '__' and e[-1:] == '_')]
        log.debug('--- CONFIGURATION ---')
        for c in cfg:
            log.debug('    %s' % c)

    def get_env_var(self, name, default = 'XXXX'):
        ## XXX/bowei consolidtate this with the other 
        if not name in os.environ:
            if default == 'XXXX':
                raise Exception('Missing configuration variable in ' + 
                                'environment: %s' % name)
            else:
                return default
        return os.environ[name].strip()

    def sync_opts_with_db(self, db):
        """Put common options into the database."""
        db.exec_sql('DROP TABLE IF EXISTS neon_metadata;')
        db.exec_sql('''CREATE TABLE neon_metadata (
                       name VARCHAR(40),
                       value VARCHAR(255)
                   );''')
        db.commit()
        db.exec_sql("INSERT INTO neon_metadata VALUES ('id', '%s');" %
                    self.id_)
        db.commit()

    def print_usage(self):
        print """sync [options...]
        
Transport connection management daemon. Note: command line options
override environmental variables.

  options:
    --help                    Show this usage message.
    --debug                   Log debugging information.
    --init-db                 If this is set, the metadata DB will be dropped.
    --type-file=<file>        default = (blank)
    --id=<id>                 default = unassigned_id
    --tx-addr=<addr>:<port>   default = localhost:7000, if the addr is a file
                              path, then a UNIX domain socket will be used
    --quit-after-init         exit after initializing DB tables
    
  environmental variables:

    NEON_ID

        Node id. This must be the same for all components.

    NEON_TX_ADDR

        <address>:<port> for the transport daemon or if the addr is a
        file path, then a UNIX domain socket will be used.

    NEON_DB_TYPE, NEON_DB_/opts/

        The type of the database {mysql, sqlite} and options specific
        to the database.

    NEON_TYPE_FILE

        Configuration file which contains all of the type construction
        information.

    NEON_SYNC_INTERVAL

        How often to sync for new local atoms will occur.
"""
